import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/Home.vue'
import store from '@/store'

const authUrls=['/editor','/homepage','/message','/project']
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
    },{path: '/', redirect: '/home'},
    {
      path: '/search', name:'search', component: () => import('@/views/Search.vue')
    },
    {
      path: '/center',
      name: 'center',
      component: () => import('@/views/Center.vue'),
      children:[
        {path:'/homepage',name:'homepage',component:()=>import('@/views/PersonCenter/HomePage.vue')},
        {path:'/center',redirect:'/homepage'},
        {path:'/message',name:'message',component:()=>import('@/views/PersonCenter/Message.vue')},
        {path:'/project',name:'project',component:()=>import('@/views/PersonCenter/ProjectList.vue')},
        {path:'/donation',name:'donation',component:()=>import('@/views/PersonCenter/Donation.vue')}
      ]
    },
    {path:'/editor',name:'editor',component:()=>import('@/views/Editor.vue')},
    {
      path:'/loginregister',
      name:'loginregister',
      component:()=>import('@/views/LoginRegister.vue'),
      children:[
        {path:'/register',name:'register',component:()=>import('@/views/LoginRegister/PersonRegister.vue')},
        {path:'/login',name:'login',component:()=>import('@/views/LoginRegister/PersonLogin.vue')}
      ]
    },{path:'/loginregister',redirect:'/login'},
    {path:'/projectdetail',name:'projectdetail',component:()=>import('@/views/ProjectDetail.vue')},
  ],
})
router.beforeEach((to, from, next) => {
  if(!authUrls.includes(to.path)){next();return;}
  const userInfo = JSON.parse(localStorage.getItem('User'))||store.state.User.user;
  if(userInfo.msg && userInfo.code){next()}
  else{next('/login')}//没有登录权限，跳转到登录页面
})

export default router
